package com.zbkj.service.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bx.imclient.IMClient;
import com.bx.imcommon.model.IMNoticeMessage;
import com.bx.imcommon.model.IMPrivateMessage;
import com.bx.imcommon.model.IMUserInfo;
import com.zbkj.common.enums.MessageType;
import com.zbkj.common.model.notice.Notice;
import com.zbkj.common.model.notice.NoticeType;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.response.NoticeResponse;
import com.zbkj.common.session.SessionContext;
import com.zbkj.common.session.UserSession;
import com.zbkj.common.util.BeanUtils;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.common.vo.PrivateMessageVO;
import com.zbkj.service.dao.NoticeMapper;
import com.zbkj.service.service.INoticeService;
import com.zbkj.service.service.INoticeTypeService;
import com.zbkj.service.service.OrderDetailService;
import com.zbkj.service.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author my
 * @date 2024-04-07
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper,Notice> implements INoticeService
{
    @Autowired
    private INoticeTypeService noticeTypeService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private RedisUtil redisUtil;

    private final IMClient imClient;
    @Override
    public void pullNotice(Long minId) {
        UserSession session = SessionContext.getSession();
//        if(!imClient.isOnline(session.getUserId())){
//            throw new GlobalException(ResultCode.PROGRAM_ERROR, "网络连接失败，无法拉取离线消息");
//        }

        // 开启加载中标志
        this.sendLoadingMessage(true);
        // 获取当前用户的消息
        LambdaQueryWrapper<Notice> queryWrapper = Wrappers.lambdaQuery();
        // 只能拉取最近1个月的1000条消息
        Date minDate = DateUtils.addMonths(new Date(), -1);
        queryWrapper.gt(Notice::getId, minId)
                .ge(Notice::getCreateTime, minDate)
                .eq(Notice::getUserId,session.getUserId())
                .orderByDesc(Notice::getId)
                .last("limit 1000");
        List<Notice> notices = this.list(queryWrapper);
        // 消息顺序从小到大
        CollectionUtil.reverse(notices);
        // 根据类型拉取内容
        for(Notice n:notices ){
            NoticeResponse response = BeanUtils.copyProperties(n, NoticeResponse.class);
            if(n.getTypeId()!=0){
                if(redisUtil.exists("noticeType-"+n.getTypeId())){
                    NoticeType noticeType = redisUtil.get("noticeType-"+n.getTypeId());
                    response.setContent(noticeType.getContent());
                    response.setTitle(noticeType.getTitle());
                }else {
                    NoticeType noticeType = noticeTypeService.getById(n.getTypeId());
                    response.setContent(noticeType.getContent());
                    response.setTitle(noticeType.getTitle());
                    redisUtil.set("noticeType-" + n.getTypeId(), noticeType);
                }
            }
            List<OrderDetail> list = orderDetailService.getByOrderNo(n.getOrderNo());
            response.setImage(list.get(0).getImage());
            //推送等待拉取
            IMNoticeMessage<NoticeResponse> sendMessage = new IMNoticeMessage<>();
            sendMessage.setRecvId(session.getUserId());
            sendMessage.setData(response);
            //            PrivateMessageVO vo = BeanUtils.copyProperties(m, PrivateMessageVO.class);
//            IMPrivateMessage<PrivateMessageVO> sendMessage = new IMPrivateMessage<>();
//            sendMessage.setSender(new IMUserInfo(m.getSendId(), IMTerminalType.WEB.code()));
//            sendMessage.setRecvId(session.getUserId());
//            sendMessage.setRecvTerminals(Arrays.asList(session.getTerminal()));
//            sendMessage.setSendToSelf(false);
//            sendMessage.setData(vo);
//            sendMessage.setSendResult(true);
            imClient.sendNoticeMessage(sendMessage);
        }
        // 关闭加载中标志
        this.sendLoadingMessage(false);
        log.info("拉取通知消息，用户id:{},数量:{}", session.getUserId(), notices.size());
    }

    private void sendLoadingMessage(Boolean isLoadding){
        UserSession session = SessionContext.getSession();
        PrivateMessageVO msgInfo = new PrivateMessageVO();
        msgInfo.setType(MessageType.LOADDING.code());
        msgInfo.setContent(isLoadding.toString());
        IMPrivateMessage sendMessage = new IMPrivateMessage<>();
        sendMessage.setSender(new IMUserInfo(session.getUserId(), session.getTerminal()));
        sendMessage.setRecvId(session.getUserId());
        sendMessage.setRecvTerminals(Arrays.asList(session.getTerminal()));
        sendMessage.setData(msgInfo);
        sendMessage.setSendToSelf(false);
        sendMessage.setSendResult(false);
        imClient.sendPrivateMessage(sendMessage);
    }
}
